package cn.cloud9.opencloud.common.api;

import java.io.Serializable;
import java.text.MessageFormat;

/**
 * @author OnCloud9
 * @description
 * @project Open-Cloud
 * @date 2022年04月16日 13:18
 */
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -1815281261529095206L;
    private static final String SUCCESS = "success";
    private static final String ERROR = "error";

    private String status;
    private Integer code;
    private String message;
    private T data;

    protected Result() {}

    public static <T> Result<T> getInstance() {
        return new Result<T>();
    }

    public Result<T> success() {
        final ResultMessage success = ResultMessage.SUCCESS;
        this.status = SUCCESS;
        this.code = success.getCode();
        this.message = success.getMessage();
        return this;
    }

    public Result<T> success(T data) {
        this.success();
        this.data = data;
        return this;
    }

    public Result<T> error() {
        final ResultMessage error = ResultMessage.SYSTEM_ERROR;
        this.status = ERROR;
        this.code = error.getCode();
        this.message = error.getMessage();
        return this;
    }

    public Result<T> error(ResultMessage errorMessage) {
        final ResultMessage error = ResultMessage.SYSTEM_ERROR;
        this.status = ERROR;
        this.code = error.getCode();
        this.message = error.getMessage();
        return this;
    }

    public Result<T> error(ResultMessage errorMessage, Object ... args) {
        this.error(errorMessage);
        this.message = MessageFormat.format(errorMessage.getMessage(), args);
        return this;
    }

    public String getStatus() {
        return status;
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
